package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 回调机制示例
 *
 * @author yangyunjiao
 */
public class CallbackExample {
    public static void main(String[] args) throws InterruptedException {
        SettableFuture<String> future = SettableFuture.create();

        // 添加回调
        Futures.addCallback(future, new FutureCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("回调成功: " + result);
            }

            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("回调失败: " + throwable.getMessage());
            }
        }, MoreExecutors.directExecutor());

        // 模拟设置结果
        new Thread(() -> {
            try {
                Thread.sleep(1000);
                if (new Random().nextBoolean()) {
                    throw new RuntimeException("回调测试失败");
                }

                future.set("回调测试成功");
            } catch (Exception e) {
                future.setException(e);
            }
        }).start();

        TimeUnit.SECONDS.sleep(2);
    }
}
